// import { message } from "antd";
import axios from "axios";
import { ERROR_MESSAGE, ERROR_TYPE } from "./constants";
import { message } from "antd";
import { clearUser } from "@/store/modules/userStore";

const instance = axios.create({
  baseURL: "http://localhost:5000",
  timeout: 10 * 1000,
  withCredentials: true,
});

// 处理请求参数，讲请求参数中的变量替换为实际值，如：/api/get/{id}，将{id}替换为params中的值
instance.interceptors.request.use((config) => {
  let url = config.url;
  let params = config.params;
  url = url.replace(/\{(\w+)\}/g, function (match, $1) {
    if (params[$1]) {
      let value = params[$1];
      delete params[$1];
      return encodeURIComponent(value);
    }
  });
  config.url = url;
  return config;
});

// 提取请求方法和url
instance.interceptors.request.use((config) => {
  const urlConfig = config.url.split(/\s+/);
  if (urlConfig.length > 1) {
    config.method = urlConfig[0].toLowerCase();
    config.url = urlConfig[1];
  }
  return config;
});

instance.interceptors.response.use(
  (response) => {
    const { data, msg, success } = response.data;
    if (success) {
      return data;
    }
    message.error(msg || ERROR_MESSAGE[500]);
    return Promise.reject({
      msg: msg || ERROR_MESSAGE[500],
      type: ERROR_TYPE.SERVER,
      status: response.status,
    });
  },
  (error) => {
    let errorMessage = ERROR_MESSAGE[500];
    if (error.response) {
      switch (error.response.status) {
        case 401:
          // 清除本地用户信息
          clearUser();
          errorMessage = ERROR_MESSAGE[401];
          message.error(ERROR_MESSAGE[401] + "，正在前往登录页面...");
          setTimeout(() => {
            window.location.href = "/user/login";
          }, 2000)
          break;
        case 404:
          errorMessage = ERROR_MESSAGE[404];
          message.error(ERROR_MESSAGE[404]);
          break;
        default:
          // message.error(ERROR_MESSAGE[500]);
          break;
      }
    }
    return Promise.reject({
      // msg: errorMessage,
      msg: error.response ? error.response.data.msg : errorMessage,
      type: ERROR_TYPE.NETWORK,
      status: error.response ? error.response.status : 500,
    });
  }
);

export default instance;
